<?php
namespace app\system\controller;

use think\Request;

class DeptController extends BaseController
{
    private $deptModel;

    /**
     * 初始化
     */
    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->deptModel = new \app\common\model\DeptModel();
    }

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {
        $map = [];
        $query        = $this->request->request();
        $searchKey    = $this->request->param('search_key');
        $searchText   = $this->request->param('search_text');
        if (!empty($searchKey) && !empty($searchText)) $map[$searchKey]     = ['like', '%' . $searchText . '%'];
        $list = $this->deptModel->where($map)->paginate(12, false, ['query' => $query]);
        $this->assign('query', $query);
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            try{
                $this->deptModel->addData($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('添加成功！',url('index'));
        }
        return $this->fetch();
    }

    /**
     * 修改
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $data   = $this->request->param();
            try{
                $this->deptModel->editData($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('修改成功！', url('index'));
        }
        $idKey = $this->request->param('dept_id/d');
        $info = $this->deptModel->get($idKey);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del(){
        $idKey = $this->request->param('dept_id/d');
        if($idKey>0){
            try{
                $map['dept_id']=$idKey;
                $this->deptModel->delData($map);
                $this->success('操作成功！');
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }else{
            $this->error('参数错误！');
        }
    }
}